package com.veryUsedCar.filter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.veryUsedCar.data.Result;
import com.veryUsedCar.enums.ConstantEnum;
import com.veryUsedCar.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Set;

//放入spring容器中
//需要 实现 GlobalFilter 全局过滤器接口, Ordered过滤器顺序接口接口
@Component
public class TokenFilter implements GlobalFilter, Ordered {

    @Autowired
    private JwtUtil jwtUtil;

    @Value("#{'${gateway.excludes.url}'.empty ? null : '${gateway.excludes.url}'.split(',')}")
    private Set<String> urlSet;

    private PathMatcher pathMatcher = new AntPathMatcher();
    //过滤
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取reuqest请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取当前路径
        String path = request.getURI().getPath();
        //遍历set集合
         for (String url : urlSet) {
            if (pathMatcher.match(url,path)){
                return chain.filter(exchange);
            }
        }
        //从请求头获取token
        String token = request.getHeaders().getFirst("token");
        //检查token是否为空
        if (StrUtil.isBlank(token)) {
            return denyAccess(exchange);
        }

        try {
            jwtUtil.parseJwt(token);
        } catch (Exception e) {
            //解析失败抛出异常
            return denyAccess(exchange);
        }

        //  放过
        return chain.filter(exchange);
    }

    //过滤器执行顺序 数字越小越先执行
    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * 拦截并返回自定义的json字符串
     * 打回去,不通过
     */
    private Mono<Void> denyAccess(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //这里在返回头添加编码，否则中文会乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        byte[] bytes = JSONObject.toJSONBytes(Result.build(ConstantEnum.NOT_LOGGED_IN), SerializerFeature.WriteMapNullValue);
        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(buffer));
    }

}